<style lang="less">
@import "./hospital.less";
@import "../../styles/common.less";
</style>
<style scoped>
.info-row {
  display: flex;
  justify-content: space-between;
  line-height: 2;
  padding: 0 24px;
}
.margin-top-10 {
  margin-top: 10px;
}
.card-title {
  height: auto;
}
</style>

<template>
    <div class="home-main">
        <Row :gutter="10" class="margin-top-10">
            <Col :md="24" :lg="8">
                <Card :style="{ minHeight: '285px'}">
                    <p slot="title" class="card-title">
                        <Icon type="android-funnel"></Icon>
                        选择设备
                    </p>
                    <div>
                        <Select v-model="dept" style="width:90%" placeholder="所属科室" filterable @on-change="filterDevice">
                            <Option v-for="item in deptList" :value="item.deptId" :key="item.deptId">{{ item.deptName }}</Option>
                        </Select>
                    </div>
                    <div class="margin-top-10">
                        <Select v-model="category" style="width:90%" placeholder="设备类型" filterable @on-change="filterDevice">
                            <Option v-for="item in categoryList" :value="item.id" :key="item.id">{{ item.name }}</Option>
                        </Select>
                    </div>
                    <div class="margin-top-10" >
                        <Select v-model="selectedId" style="width:90%" placeholder="设备ID" filterable>
                            <Option v-for="item in idList" :value="item" :key="item">{{ item }}</Option>
                        </Select>
                    </div>
                    <!-- <div class="margin-top-10" style="width:90%">
                        <DatePicker type="datetimerange" placeholder="查询时间范围" style="width: 100%" :options="futureDays" v-model="selectedRange"></DatePicker>
                    </div> -->
                    <div class="margin-top-10" style="width:90%">
                        <!-- <span><Button type="primary" icon="search" @click="search" :disabled="(!selectedId||selectedRange.filter((item)=>{return item!==''}).length!==2)">筛选</Button></span> -->
                        <span><Button type="primary" icon="search" @click="search" :disabled="!selectedId">筛选</Button></span>
                        <Button type="ghost" >取消</Button>
                    </div>
                </Card>
            </Col>
            <Col :md="24" :lg="8" :style="{marginBottom: '10px'}">
               <Row>
                  <Card :padding="0" :style="{ minHeight: '285px'}">
                      <p slot="title" class="card-title">
                        <Icon type="ios-pulse-strong"></Icon>
                        实时设备数据<span>（刷新于{{deviceDataTime}}）</span>
                        <Button icon="ios-cloud-download-outline" type="text" size="large" style="position: absolute; right: 8px; top: 8px;"></Button>
                      </p>
                      <div style="padding: 12px;" class="event-table">
                        <div class="info-row">
                            <span class="warning-name" style="font-weight: bold">状态</span>
                            <span class="warning-type"><Tag :color="deviceData.status==='N/A'?'lightgrey':'green'">{{deviceData.status}}</Tag></span>
                        </div>
                        <div class="info-row">
                            <span class="warning-name" style="font-weight: bold">电压</span>
                            <span class="warning-type">{{deviceData.U}} V</span>
                        </div>
                        <div class="info-row">
                            <span class="warning-name" style="font-weight: bold">电流</span>
                            <span class="warning-type">{{deviceData.I}} mA</span>
                        </div>
                        <div class="info-row">
                            <span class="warning-name" style="font-weight: bold">电功率</span>
                            <span class="warning-type">{{deviceData.P}} W</span>
                        </div>
                        <div class="info-row">
                            <span class="warning-name" style="font-weight: bold">使用预约({{deviceData.used_hour}}/{{deviceData.reserved_hour}}小时)</span>
                            <div style="width: 50%">
                              <Progress :percent="!!deviceData.reserved_hour?deviceData.used_hour/deviceData.reserved_hour*100:0" status="active" hide-info></Progress>
                            </div>
                        </div>
                        <div class="info-row">
                            <span class="warning-name" style="font-weight: bold">近24h用电量</span>
                            <span class="warning-type">{{deviceData.total_Q}} kWh</span>
                        </div>
                        <div class="info-row">
                            <span class="warning-name" style="font-weight: bold">设备位置</span>
                            <span class="warning-type">{{deviceData.location}} <Icon type="location" size="18" color="#2d8cf0" style="cursor: pointer"></Icon> </span>
                        </div>
                      </div>
                  </Card>
                </Row>
            </Col>
            <Col :md="24" :lg="8" :style="{marginBottom: '10px'}">
              <Card :padding="0"  :style="{ minHeight: '285px'}">
                <p slot="title" class="card-title">
                    <Icon type="clipboard"></Icon>
                    设备资料
                </p>
                <div style="padding: 12px;" class="event-table">
                  <div class="info-row">
                      <span class="warning-name" style="font-weight: bold">额定电压</span>
                      <span class="warning-type">{{deviceData.nominal_U}} V</span>
                  </div>
                  <div class="info-row">
                      <span class="warning-name" style="font-weight: bold">额定电流</span>
                      <span class="warning-type">{{deviceData.nominal_I}} mA</span>
                  </div>
                  <div class="info-row">
                      <span class="warning-name" style="font-weight: bold">额定电功率</span>
                      <span class="warning-type">{{deviceData.nominal_P}} W</span>
                  </div>
                  <div class="info-row">
                      <span class="warning-name" style="font-weight: bold">使用情况</span>
                      <chart :options="calendarOption" auto-resize style="position: absolute; height: 130px; width: calc(100% - 100px); bottom: 0; "></chart>
                  </div>
                </div>
              </Card>
            </Col>
        </Row>
        <Row class="margin-top-10">
            <Card>
                <p slot="title" class="card-title">
                  <Tabs type="card" :value="panel1Mode" v-model="panel1Mode">
                    <TabPane name="I" label="电流变化"></TabPane>
                    <TabPane name="U" label="电压变化"></TabPane>
                    <TabPane name="P" label="电功率变化"></TabPane>
                    <TabPane name="Q" label="用电量变化"></TabPane>
                  </Tabs>
                </p>
                <div>
                  <chart v-if="panel1Mode==='I'"  :options="historyOption" auto-resize style="height: 350px; width: 100% "></chart>
                  <chart v-if="panel1Mode==='U'"  :options="historyOptionU" auto-resize style="height: 350px; width: 100% "></chart>
                  <chart v-if="panel1Mode==='P'"  :options="historyOptionP" auto-resize style="height: 350px; width: 100% "></chart>
                  <chart v-if="panel1Mode==='Q'" :options="historyOptionQ" auto-resize style="height: 350px; width: 100% "></chart>
                </div>
            </Card>
        </Row>
    </div>
</template>

<script>
import Moment from "moment";
import { calendarOption } from "./data/calendar";
import { historyOption } from "./data/history";
import { historyOptionQ } from "./data/history-bar";
import io from "socket.io-client";

export default {
  name: "home",
  components: {},
  async mounted() {
    this.deptList = (await this.$getRemoteData(
      `${this.$mapServer}/equip/services/config/deptList`
    )).data;
    this.categoryList = (await this.$getRemoteData(
      `${this.$mapServer}/equip/services/config/deviceCategory/0/0/9999999`
    )).data.data;
    this.calendarData = this.calendarOption.series[0].data;
    this.calendarOption.series[0].data = [];
  },
  data() {
    return {
      futureDays: {
        disabledDate(date) {
          return date.valueOf() > Date.now();
        }
      },
      socket: undefined,
      panel1Mode: "I",
      calendarOption,
      historyOption,
      historyOptionU: JSON.parse(JSON.stringify(historyOption)),
      historyOptionP: JSON.parse(JSON.stringify(historyOption)),
      historyOptionQ,
      selectedId: "",
      selectedRange: [],
      dept: "",
      category: "",
      idList: [],
      categoryList: [],
      deptList: [],
      calendarData: [],
      deviceData: {
        status: "N/A",
        U: "",
        I: "",
        P: "",
        nominal_U: "",
        nominal_I: "",
        nominal_P: "",
        total_Q: "",
        used_hour: "",
        reserved_hour: "",
        location: "N/A",
        usage_calendar: [],
        wsUpdate: undefined
      },
      deviceBasicInfo: {},
      deviceDataTime: "",
      lastestDataId: ""
    };
  },
  computed: {
    avatorPath() {
      return localStorage.avatorImgPath;
    }
  },
  methods: {
    getVirtulData() {
      const now = new Moment();
      const start = new Moment().subtract(3, "month");
      const dayTime = 3600 * 24;
      const data = [];
      for (let time = start.unix(); time <= now.unix(); time += dayTime) {
        data.push([
          Moment.unix(time).format("YYYY-MM-DD"),
          Math.random() > 0.3 ? (Math.random() * 20).toFixed(2) : 0
        ]);
      }
      return data;
    },
    truncateDateData(data, start, end) {
      let result = {
        dates: [],
        data: []
      };
      // 截取，最后添加范围外最新的数据一项
      let firstDataIndex = data.data.length - 1;
      for (let i = 0; i < data.data.length; i++) {
        let k = false;
        if (
          Moment(data.dates[i]).unix() < end.unix() &&
          Moment(data.dates[i]).unix() > start.unix()
        ) {
          result.dates.push(data.dates[i]);
          result.data.push(data.data[i]);
          if (!k) firstDataIndex = i - 1 > 0 ? i - 1 : 0;
        }
      }
      result.dates.push(data.dates[firstDataIndex]);
      result.data.push(data.data[firstDataIndex]);
      let resultAfterNorm = {
        dates: [],
        data: []
      };
      for (
        let now = new Moment().subtract(5, "minutes");
        now.unix() < end.unix();
        now = now.add(1, "second")
      ) {
        resultAfterNorm.dates.push(now.format("HH:mm:ss"));
        if (now < Moment(result.dates[result.dates.length - 2])) {
          resultAfterNorm.data.push(result.data[result.data.length - 1]);
        } else {
          if (result.data.length > 2) {
            result.dates.pop();
            result.data.pop();
          }
          resultAfterNorm.data.push(result.data[result.data.length - 1]);
        }
      }
      return resultAfterNorm;
    },
    async search() {
      if (!this.selectedId) return;
      if (!!this.wsUpdate) clearInterval(this.wsUpdate);
      if (this.socket) this.socket.close();
      this.deviceBasicInfo = (await this.$getRemoteData(
        `https://yxys.io/api/equip/device/v1/${this.selectedId}`
      )).data;
      this.deviceDataTime = new Moment().format("HH:mm:ss");
      if (!!this.deviceBasicInfo.powerStrip) {
        this.socket = io(
          `wss://yxys.io?id=${this.deviceBasicInfo.powerStrip}`,
          {
            path: "/api/deviceData",
            forceNew: true
          }
        );
        this.socket.on("news", data => {
          this.deviceData.I = data.I;
          this.deviceData.U = data.U;
          this.deviceData.P = data.P;
          this.historyOption.series[0].data.shift();
          this.historyOption.xAxis.data.shift();
          this.historyOption.series[0].data.push(data.I);
          this.historyOption.xAxis.data.push(data.time);
          this.historyOptionU.series[0].data.shift();
          this.historyOptionU.xAxis.data.shift();
          this.historyOptionU.series[0].data.push(data.U);
          this.historyOptionU.xAxis.data.push(data.time);
          this.historyOptionP.series[0].data.shift();
          this.historyOptionP.xAxis.data.shift();
          this.historyOptionP.series[0].data.push(data.P);
          this.historyOptionP.xAxis.data.push(data.time);
          if (this.historyOptionQ.series[0].data.length > 300) {
            this.historyOptionQ.series[0].data.shift();
            this.historyOptionQ.xAxis.data.shift();
          }
          if (this.lastestDataId !== data.id) {
            this.historyOptionQ.series[0].data.push(this.historyOptionQ.series[0].data[this.historyOptionQ.series[0].data.length-1] + parseFloat(data.Q));
            this.lastestDataId = data.id;
            this.deviceData.total_Q = parseFloat(this.deviceData.total_Q) +  parseFloat(data.Q);
          } else {
            this.historyOptionQ.series[0].data.push(this.historyOptionQ.series[0].data[this.historyOptionQ.series[0].data.length-1]);
          }
          this.historyOptionQ.xAxis.data.push(data.time);
          this.deviceDataTime = data.time;
        });
      }
      const startDate = new Moment().subtract(1, "day").format("YYYY-MM-DD");
      const endDate = new Moment().format("YYYY-MM-DD");
      const deviceData = (await this.$getRemoteData(
        `${this.$mapServer}/equip/services/device/deviceData?id=${
          this.selectedId
        }`
      )).data;
      let historyI = (await this.$getRemoteData(
        `${this.$mapServer}/equip/services/device/deviceHistoryI?id=${
          this.selectedId
        }&start=${startDate}&end=${endDate}`
      )).data;
      let historyU = (await this.$getRemoteData(
        `${this.$mapServer}/equip/services/device/deviceHistoryU?id=${
          this.selectedId
        }&start=${startDate}&end=${endDate}`
      )).data;
      let historyP = (await this.$getRemoteData(
        `${this.$mapServer}/equip/services/device/deviceHistoryP?id=${
          this.selectedId
        }&start=${startDate}&end=${endDate}`
      )).data;
      let historyQ = (await this.$getRemoteData(
        `${this.$mapServer}/equip/services/device/deviceHistoryQ?id=${
          this.selectedId
        }&start=${startDate}&end=${endDate}`
      )).data;

      const past10 = new Moment().subtract(10, "minutes");
      historyI = this.truncateDateData(historyI, past10, new Moment());
      historyU = this.truncateDateData(historyU, past10, new Moment());
      historyP = this.truncateDateData(historyP, past10, new Moment());
      // historyQ = this.truncateDateData(historyQ, past10, new Moment());
      this.deviceData = {
        status: "正常",
        U: parseFloat(deviceData.U).toFixed(2),
        I: parseFloat(deviceData.I).toFixed(2),
        P: parseFloat(deviceData.P).toFixed(2),
        total_Q: historyQ.data[0],
        used_hour: parseFloat(deviceData.used_hour / 10).toFixed(1),
        reserved_hour: parseFloat(deviceData.reserved_hour).toFixed(1),
        location: "综合楼1楼",
        nominal_U: 220,
        nominal_I: 420,
        nominal_P: 120
      };
      this.calendarOption.series[0].data = this.getVirtulData();
      this.historyOption.series[0].data = historyI.data;
      this.historyOption.xAxis.data = historyI.dates;
      this.historyOptionP.series[0].data = historyP.data;
      this.historyOptionP.xAxis.data = historyP.dates;
      this.historyOptionU.series[0].data = historyU.data;
      this.historyOptionU.xAxis.data = historyU.dates;
    },
    async filterDevice() {
      this.idList = (await this.$getRemoteData(
        `${this.$mapServer}/equip/services/device/deviceFilter?dept=${
          this.dept
        }&category=${this.category}`
      )).data;
    }
  },
  beforeDestroy() {
    if (this.socket) this.socket.close();
  }
};
</script>
